package logic

import (
	"common/global"
	"common/model"
	"common/utils"
	"context"
	"errors"
	user "user_server/proto"
)

// Register 用户注册（事务封装）
func (s *UserServer) Register(ctx context.Context, req *user.RegisterRequest) (*user.RegisterResponse, error) {
	// 参数校验
	if len(req.Tel) != 11 || len(req.Password) < 6 {
		return nil, errors.New("参数格式错误")
	}

	tx := global.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 检查手机号唯一性
	var existCount int64
	tx.Model(&model.User{}).Where("tel = ?", req.Tel).Count(&existCount)
	if existCount > 0 {
		tx.Rollback()
		return nil, errors.New("手机号已注册")
	}

	// 密码加密
	hashedPassword := utils.EnPwdCode([]byte(req.Password))

	// 创建用户
	newUser := model.User{
		Tel:      req.Tel,
		Passwd:   hashedPassword,
		Nickname: "用户_" + req.Tel[len(req.Tel)-4:],
	}
	if err := tx.Create(&newUser).Error; err != nil {
		tx.Rollback()
		return nil, errors.New("用户创建失败")
	}

	if err := tx.Commit().Error; err != nil {
		return nil, errors.New("事务提交失败")
	}

	return &user.RegisterResponse{Success: true}, nil
}

// Login 用户登录
func (s *UserServer) Login(ctx context.Context, req *user.LoginRequest) (*user.LoginResponse, error) {
	var u model.User
	tel, err := u.FindUserByTel(req.Tel)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	// 验证密码
	if tel.Passwd != utils.EnPwdCode([]byte(req.Password)) {
		return nil, errors.New("密码错误")
	}

	return &user.LoginResponse{
		UserId:   int32(tel.ID),
		Nickname: tel.Nickname,
		Avatar:   tel.Avatar,
	}, nil
}
